home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9655 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  88 lines

  1. Path: news.WARWICK.NET!usenet
  2. From: acorn@warwick.net (Peter Kohlberger)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: malloc question
  5. Date: Tue, 12 Mar 1996 16:35:35 GMT
  6. Organization: Warwick Online
  7. Message-ID: <4i492m$9jl@news1.warwick.net>
  8. References: <4htonk$350@news.hklink.net>
  9. NNTP-Posting-Host: t9-15.warwick.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. alex@station.net (Alex Chu) wrote:
  13. >Hi everybody,
  14.  
  15. >I have a question for the following snip C program.
  16.  
  17. >typedef struct item {
  18. >  int val;
  19. >  struct item *next;
  20. >} ITEM, *PITEM;
  21.  
  22. >main()
  23. >{
  24. >  PITEM head, current;
  25. >  head=(PITEM) malloc(sizeof(ITEM));
  26. >            ^^^^^^^
  27. >  head->val=1;
  28. >}
  29.  
  30. >I want to know why need to use the type casting PITEM in front of the
  31. >malloc ?  Please help!
  32.  
  33. Basically, you need the cast because head is of type "pointer to ITEM"
  34. and malloc returns type "pointer to void".  If you try it without the
  35. cast, your compiler will complain "cannot convert *void to *ITEM".
  36. This is just the mechanics of the answer though, and I suspect this
  37. is not what really puzzles you.
  38.  
  39. Without the cast, you can not convert *void into *ITEM; with the cast,
  40. you are allowed to do the conversion.  If the conversion is allowed in
  41. one manner, why is it not allowed in the other manner?
  42.  
  43. The answer is (mostly) so that the compiler can catch your errors.
  44. While a pointer to void can be converted to a pointer to any type of
  45. object, it's desirable to ensure that the conversion is the actual
  46. intent of the programmer.  
  47.  
  48. Consider the following:
  49.  
  50. typedef struct item1 {
  51.   int val;
  52.   struct item *next;
  53. } ITEM1, *PITEM1;
  54.  
  55. typedef struct item2 {
  56.   int val;
  57.   struct item *next;
  58.   char text[40];
  59. } ITEM2, *PITEM2;
  60.  
  61. main()
  62. {
  63.   PITEM1 head1;
  64.   PITEM2 head2;
  65.  
  66.   head1 =(PITEM1)malloc(sizeof(ITEM1));
  67.   head1->val=1;
  68.  
  69.   head2 =malloc(sizeof(ITEM1));     /* illegal */
  70.   strcpy(head2->text,"Some text for here"); 
  71.  
  72.   return(0);
  73. }
  74.  
  75. If the above call to malloc() without a cast was allowed, head2 would
  76. be allocated 6 bytes when it needs 46 bytes (in my environment).
  77. Requiring the cast changes the code to:
  78.  
  79.   head2 =(PITEM1)malloc(sizeof(ITEM1)); 
  80.  
  81. which will result in a compiler error.
  82.  
  83. Peter Kohlberger
  84. acorn@warwick.net
  85.  
  86.  
  87.  
  88.